package com.stox.charting.ui.swing.model;

import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import prefuse.util.ui.JRangeSlider;

public class Zoom implements MouseWheelListener{

	private static final int maximum = 100;
	private static final int minimum = 1;
	
	private int oldValue = 50;
	private int value = 50;
	private JRangeSlider slider;
	
	public Zoom(JRangeSlider slider) {
		this.slider = slider;
	}

	private void setValue(){
		value = ((slider.getHighValue() - slider.getLowValue())*100)/(slider.getMaximum() - slider.getMinimum());
	}
	
	public void out(){
		setValue();
		if(value < maximum){
			oldValue = value;
			value++;
			if(!apply()){
				value--;
			}
		}
	}

	public void in(){
		setValue();
		if(value > minimum){
			oldValue = value;
			value--;
			if(!apply()){
				value++;
			}
		}
	}
	
	@Override
	public void mouseWheelMoved(MouseWheelEvent e) {
		e.consume();
		int clicks = e.getWheelRotation();
		int newValue = value + clicks;
		if(newValue < maximum && newValue > minimum){
			oldValue = value;
			value = newValue;
			apply();
		}
	}
	
	public boolean apply(){
		int low = slider.getLowValue();
		int high = slider.getHighValue();
		int max = slider.getMaximum();
		int min = slider.getMinimum();
		
		int difference = (high - low);
		difference -= difference*value/oldValue;
		difference /= 2;
		high -= difference;
		low += difference;
		
		if(high > max && low >= min){
			slider.setRange(low + difference, high + difference);
			return true;
		}else if(high <= max && low < min){
			slider.setRange(low - difference, high - difference);
			return true;
		}else if(high <= max && low >= min){
			slider.setRange(low, high);
			return true;
		}
		return false;
	}
	
}
